package main

//测试用例
//没有设置按时发消息的测试

import (
	"bufio"
	"flag"
	"fmt"
	"github.com/gorilla/websocket"
	"golang.org/x/net/context"
	"log"
	"os"
	"strconv"
	"sync"
)

type Connection struct {
	conn *websocket.Conn
	mu   sync.Mutex
}

var wg sync.WaitGroup

func main() {
	wg.Add(2)
	userName := flag.String("user", "error", "Input Your UserName")
	group := flag.Int("group", 1, "Input your group")
	flag.Parse()
	//origin := "http://127.0.0.1:8081"
	wsConn := "ws://127.0.0.1:8081/ws?group=" + strconv.Itoa(*group) + "&username=" + *userName
	fmt.Println(wsConn)
	conn, _, err := websocket.DefaultDialer.Dial(wsConn, nil)
	if err != nil {
		log.Println(err)
		conn.Close()
	}
	fmt.Println("请输入内容")
	var c Connection
	c.conn = conn
	cont, cancel := context.WithCancel(context.Background())
	go c.Receive(cont)
	go c.Send(cont, cancel)
	wg.Wait()
}

func Input() []byte {
	reader := bufio.NewReader(os.Stdin)
	by, _, err := reader.ReadLine()
	if err != nil {
		log.Println(err)
		return []byte{}
	}
	return by
}

func (c *Connection) Receive(ctx context.Context) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println("ctx.Done()")
			wg.Done()
			return
		default:
			_, msg, err := c.conn.ReadMessage()
			if err != nil {
				log.Println(err)
				return
			}
			fmt.Println("receive:", string(msg))
		}
	}
}

func (c *Connection) Send(ctx context.Context, cancel context.CancelFunc) {
	for {
		input := Input()
		if string(input) == "-1" {
			wg.Done()
			cancel()
			return
		}
		err := c.conn.WriteMessage(websocket.TextMessage, []byte(input))
		if err != nil {
			log.Println(err)
			return
		}
		log.Println("SEND：", string(input))
	}
}

func (c *Connection) PongMessage() (err error) {
	defer log.Println("pong suc")
	//err = c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
	if err != nil {
		log.Println(err)
		return err
	}
	c.conn.WriteMessage(websocket.TextMessage, []byte("pong"))
	return
}
